<template>
  <div class="task-container">
    <div ref="readerContainer" :class="`etbreader-container ${toolbarPosition}`">
      <iframe
        ref="readerFrame"
        src="/etbreader/v1.0.3/iframe.html"
        class="etbreader"
        sandbox="allow-scripts allow-same-origin"
        allow="microphone;camera;geolocation;midi;encrypted-media;"
        frameborder="0"
      ></iframe>
    </div>
    <!-- 左边tabBar -->
    <div :class="`toolbar ${toolbarPosition}`">
      <div class="tools">
        <span class="tool" @click="switchToolbarPosition">
          &#10122;<br>置换
        </span>
        <span class="tool" @click="switchFullscreen">
          &#10123;<br>{{isFullscreenMode ? '退出全屏' : '全屏'}}
        </span>
        <span
          :class="`tool${isStatisticsVisible ? ' active' : ''}`"
          @click="switchStatisticsViewer"
        >
          &#10124;<br>统计
        </span>
        <span :disabled="etb.pageNumber <= 1" class="tool" @click="goPrevPage">
          &#10125;<br>上一页
        </span>
        <span :disabled="etb.pageNumber >= etb.pages.length" class="tool" @click="goNextPage">
          &#10126;<br>下一页
        </span>
      </div>
    </div>
    <div :style="{ display: isStatisticsVisible ? 'flex' : 'none' }" :class="`statistics ${toolbarPosition}`">
      <div class="menu">
        <div class="menu-list">
          <div
            v-for="(w, i) in statisticalWidgets" :key="i"
            :class="`menu-item${statisticalWidgetIndex === i ? ' active' : ''}`"
            @click="statisticalWidgetIndex = i"
          >
            {{w.groupName || w.widgets.map(cw => cw.displayName).join('+')}}
          </div>
        </div>
      </div>
      <iframe
        ref="statisticsViewerFrame"
        :style="{ display: statisticalWidget ? 'block' : 'none' }"
        src="/iframe.html"
        class="viewer"
        sandbox="allow-scripts allow-same-origin"
        frameborder="0"
      ></iframe>
    </div>
  </div>
</template>

<script>
import find from 'lodash.find';
import { ref, computed, reactive, onMounted } from 'vue';
import useReaderMessenger from './ReaderMessenger';
import useReaderResizer from './ReaderResizer';
import useStatisticsViewerMessenger from './StatisticsViewerMessenger';

export default {
  name: 'App',
  components: {},
  setup() {
    const etb = reactive({
      pages: [],
      pageNumber: 0,
      pageWidgets: [],
    });
    const isEtbLoaded = ref(false);
    const readerContainer = ref(null);
    const readerFrame = ref(null);

    const { loadEtb, renderPage } = useReaderMessenger(etb, readerFrame);

    const initTask = async () => {
      if (!isEtbLoaded.value) {
        loadEtb();
        isEtbLoaded.value = true;
      }
      updateReaderSize();
    };
    onMounted(initTask);

    const statisticalWidgetIndex = ref(-1);

    const statisticalWidgets = computed(() => {
      const statisticalWidgets = [];
      etb.pageWidgets.forEach((widget) => {
        if (!widget.__supportInteract) return;
        if (widget.__interactDataCollectType !== 'page') {
          statisticalWidgets.push({ displayName: widget.displayName, itemId: widget.itemId });
        } else {
          const widgetType = widget.itemId.split('-').shift();
          const condition =  { widgetType, isGrouped: true, groupName: widget.__groupName };
          const group = find(statisticalWidgets, condition);
          if (!group) {
            statisticalWidgets.push({
              ...condition,
              widgets: [{ displayName: widget.displayName, itemId: widget.itemId }]
            });
          } else {
            group.widgets.push({ displayName: widget.displayName, itemId: widget.itemId });
          }
        }
      });
      return statisticalWidgets.map(widget => {
        if (widget.isGrouped) return widget;
        return {
          widgetType: widget.itemId.split('-').shift(),
          groupName: widget.displayName,
          widgets: [widget]
        };
      });
    });

    const statisticalWidget = computed(() => statisticalWidgets.value[statisticalWidgetIndex.value]);

    const statisticsViewerFrame = ref(null);
    const isStatisticsVisible = ref(false);

    const resetPageData = () => {
      isStatisticsVisible.value = false;
      statisticalWidgetIndex.value = -1;
      etb.pageWidgets = [];
    };

    const goPrevPage = async () => {
      if (etb.pageNumber <= 1) return;
      resetPageData();
      etb.pageNumber -= 1;
      renderPage(etb.pageNumber);
    };
    const goNextPage = async () => {
      if (etb.pageNumber >= etb.pages.length) return;
      resetPageData();
      etb.pageNumber += 1;
      renderPage(etb.pageNumber);
    };

    useStatisticsViewerMessenger(etb, statisticalWidget, statisticsViewerFrame, {});

    const switchStatisticsViewer = async () => {
      if (isStatisticsVisible.value) {
        isStatisticsVisible.value = false;
      } else {
        isStatisticsVisible.value = true;
      }
    };

    const isFullscreenMode = ref(false);
    const switchFullscreen = () => {
      if (document.fullscreenElement) {
        document.exitFullscreen();
        isFullscreenMode.value = false;
      } else {
        document.documentElement.requestFullscreen();
        isFullscreenMode.value = true;
      }
    };

    const toolbarPosition = ref('right');
    const { updateReaderSize } = useReaderResizer(readerContainer, toolbarPosition);
    const switchToolbarPosition = () => {
      toolbarPosition.value = toolbarPosition.value === 'left' ? 'right' : 'left';
      updateReaderSize();
    };

    return {
      isEtbLoaded,
      etb,
      readerFrame,
      readerContainer,
      statisticsViewerFrame,
      statisticalWidgetIndex,
      statisticalWidgets,
      statisticalWidget,
      toolbarPosition,
      isStatisticsVisible,
      isFullscreenMode,
      switchToolbarPosition,
      switchFullscreen,
      switchStatisticsViewer,
      goPrevPage,
      goNextPage,
    };
  }
}
</script>

<style>

body {
  margin: 0;
}

</style>

<style lang="less" scoped>
@toolbarWidth: 70px;

.task-container {
  position: fixed;
  top: 60px;
  left: 0;
  width: 100vw;
  height: calc(100vh - 60px);
  overflow: hidden;
}

.toolbar {
  position: absolute;
  top: 0;
  right: 0;
  height: 100vh;
  width: @toolbarWidth;
  text-align: center;
  box-sizing: border-box;
  border-left: 1px solid #ddd;
  background-color: white;
  overflow: auto;

  &.folded {
    height: auto;
    top: auto;
    bottom: 0;
    width: 48px;

    .tool {
      font-size: 20px;
    }
  }

  &.left {
    right: auto;
    left: 0;
    border-left: none;
    border-right: 1px solid #ddd;

    .tool.active {
      border-left: none;
      border-right: 3px solid #1890ff;
    }
  }

  .tools {
    position: relative;
    top: 50%;
    transform: translate(0, -50%);
  }

  .tool {
    position: relative;
    display: inline-block;
    width: 100%;
    box-sizing: border-box;
    color: rgba(0, 0, 0, 0.8);
    line-height: 1.2;
    font-weight: 400;
    white-space: nowrap;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
    user-select: none;
    touch-action: manipulation;
    padding: 8px 6px;
    font-size: 14px;
    border-bottom: 1px solid #ddd;

    &:first-child {
      border-top: 1px solid #ddd;
    }

    &:hover {
      background-color: #eee;
    }

    &.active {
      background-color: #e6f7ff;
      color: #1890ff;
      border-left: 3px solid #1890ff;
    }
  }
}

.etbreader-container {
  position: relative;
  width: calc(100% - @toolbarWidth);
  height: 100%;
  overflow: hidden;
  transform-origin: top left;

  &.left {
    left: @toolbarWidth;
  }

  .etbreader {
    position: relative;
    display: block;
    margin: auto;
    width: 960px;
    height: 720px;
    top: 50%;
    transform: translate(0, -50%);
    box-sizing: content-box;
    box-shadow: 0 0 2px 1px #ddd;
  }
}

.statistics {
  position: absolute;
  top: 0;
  left: 0;
  width: calc(100% - @toolbarWidth);
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: row-reverse;

  &.left {
    left: @toolbarWidth;
    flex-direction: row;

    .menu {
      border-left: none;
      border-right: 1px solid #ddd;

      .menu-item {
        &.active {
          border-left: none;
          border-right: 3px solid #1890ff;
        }
      }
    }
  }

  .menu {
    width: 200px;
    box-sizing: border-box;
    border-left: 1px solid #ddd;
    background-color: #f8f8f8;

    .menu-list {
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }

    .menu-item {
      cursor: pointer;
      padding: 12px 10px;

      &.active {
        background-color: #e6f7ff;
        color: #1890ff;
        border-left: 3px solid #1890ff;
      }
    }
  }

  .viewer {
    display: block;
    width: calc(100% - 200px);
    height: 100%;
    box-sizing: content-box;
    background-color: white;
    overflow: auto;
  }
}

.frame-close-btn,
.frame-refresh-btn {
  position: absolute;
  width: 36px;
  height: 36px;
  line-height: 36px;
  font-size: 28px;
  color: white;
  background-color: #e91e63;
  text-align: center;
  top: 2px;
  right: 2px;
  cursor: pointer;
}

.frame-refresh-btn {
  background: #03a9f4;
  right: 48px;
}
</style>